'use strict'
const CryptoJS = require('crypto-js')

module.exports = (app) => {
  const { STRING, INTEGER, DATE } = app.Sequelize
  // 配置（重要：一定要配置详细，一定要！！！）
  const AdminUser = app.model.define('admin_user', {
    id: {
      type: INTEGER(20).UNSIGNED,
      primaryKey: true,
      autoIncrement: true
    },
    username: {
      type: STRING(30),
      allowNull: false,
      comment: '用户名'
    },
    password: {
      type: STRING,
      allowNull: false,
      comment: '密码',
      set(value) {
        // 加密
        const secret = app.config.crypto.secret
        const ciphertext = CryptoJS.HmacSHA256(value, secret).toString()
        this.setDataValue('password', ciphertext)
      }
    },
    avatar: {
      type: STRING(500),
      comment: '头像'
    },
    type: {
      type: INTEGER(1),
      defaultValue: 1,
      comment: '类型-1:管理员,2:超级管理员'
    },
    created_time: {
      type: DATE,
      get() {
        return app.formatTime(this.getDataValue('created_time'))
      }
    }
  })
  // 关联关系
  AdminUser.associate = (models) => {
    // 多对多
    AdminUser.belongsToMany(app.model.Role, {
      through: app.model.UserRole,
      foreignKey: 'uid',
      otherKey: 'rid'
    })
  }

  return AdminUser
}
